package com.fenger.sys.service.impl;

import com.fenger.sys.contast.SysConstast;
import com.fenger.sys.domain.Role;
import com.fenger.sys.mapper.RoleMapper;
import com.fenger.sys.service.RoleService;
import com.fenger.sys.utils.DataGirdView;
import com.fenger.sys.vo.RoleVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    RoleMapper roleMapper;
    @Override
    @Transactional(readOnly = true)
    public DataGirdView queryAllRole(RoleVo roleVo) {
        Page<Object> page = PageHelper.startPage(roleVo.getPage(), roleVo.getLimit());
        List<Role> roles = this.roleMapper.queryAllRole(roleVo);

        return new DataGirdView(SysConstast.SUCCESS_CODE,SysConstast.SUCCESS_MSG,page.getTotal(),roles);
    }

    @Override
    public void addRole(RoleVo roleVo) {
        this.roleMapper.insertSelective(roleVo);
    }

    @Override
    public void updateRole(RoleVo roleVo) {
        this.roleMapper.updateByPrimaryKeySelective(roleVo);
    }

    @Override
    public void deleteRole(Integer id) {
        this.roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public DataGirdView queryRoleByUserid(Integer id) {
        List<Map<String,Object>> list = new ArrayList<>();
        RoleVo roleVo = new RoleVo();
        List<Role> allRoles = this.roleMapper.queryAllRole(roleVo);

        List<Role> roles = this.roleMapper.queryRoleByUserid(id);
        for (Role role : allRoles) {
            Map<String,Object> map = new HashMap<>();
            map.put("id",role.getId());
            map.put("name",role.getName());
            map.put("remark",role.getRemark());
            map.put("LAY_CHECKED",false);
            for (Role r : roles) {
                if(role.getId()==r.getId()){
                    map.put("LAY_CHECKED",true);
                    break;
                }
            }
            System.out.println(map);
            list.add(map);
        }

        return new DataGirdView(SysConstast.SUCCESS_CODE,SysConstast.SUCCESS_MSG,0L,list);
    }

    @Override
    public List<String> queryRoleByUseridForList(Integer id) {
        List<Role> roles = this.roleMapper.queryRoleByUserid(id);
        List<String> strRoles = new ArrayList<>();
        for (Role role : roles) {
            strRoles.add(role.getName());
        }
        return strRoles;
    }
}
